﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.DirectoryServices;
using System.Reflection;
using System.Xml;
using System.Configuration;

namespace WebCompiler
{
    class Program
    {
        /// <summary>
        /// 设置config
        /// </summary>
        /// <returns></returns>
        public static bool IsNewIIS()
        {
            DirectoryEntry getEntity = new DirectoryEntry("IIS://localhost/W3SVC/INFO");
            try
            {
                double Version = Convert.ToDouble(getEntity.Properties["MajorIISVersionNumber"].Value);
                if (Version >= 7)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return true;
            }
        }
       

        public static void WebCompile()
        {
            string root = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName + "\\";
            string[] dllFiles = Directory.GetFiles(root + "bin\\", "*.dll");
            Assembly ass = null;
            Type t = null;
            string dllFile = null;
            if (dllFiles.Length > 0)
            {
                for (int i = 0; i < dllFiles.Length; i++)
                {
                    try
                    {
                        ass = Assembly.LoadFile(dllFiles[i]);
                        t = ass.GetType("NFinal.Builder", false);
                        if (t != null)
                        {
                            dllFile = dllFiles[i];
                            break;
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            if (t != null)
            {
                object builder = Activator.CreateInstance(t, root);

                MethodInfo method = t.GetMethod("Create");
                object[] pars = new object[1];
                pars[0] = IsNewIIS();
                method.Invoke(builder, pars);
            }
        }
        static void Main(string[] args)
        {
            FileInfo[] projFiles = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.GetFiles("*.csproj");
            if (projFiles.Length > 0)
            {
                Project proj = new Project();
                //添加相关dll文件
                proj.AddLibrary(projFiles[0].FullName);
                //编译文件
                WebCompile();
            }
            else
            {
                Console.WriteLine("请把NFinal放到项目根目录下");
                Console.ReadKey();
            }
        }
    }
}
